<template>
    <a-spin :spinning="loading" size="large">
      <van-form @submit="onSubmit" ref="formRef">
        <h3>1.问题地址</h3>
        <van-cell-group inset>
          <van-field readonly v-model="faceList.placeName" placeholder="请输入问题地址"></van-field>
        </van-cell-group>
        <h3>2.问题描述</h3>
        <van-cell-group inset>
          <van-field readonly v-model="faceList.checkContent" type="textarea" rows="2" autosize placeholder="请输入问题描述"></van-field>
        </van-cell-group>
        <h3>3.问题照片</h3>
        <van-cell-group inset>
          <a-image :width="150" v-for="item in JSON.parse(faceList.imgsIdBase64)" :src="'data:image/jpg;base64,' + item"></a-image>
        </van-cell-group>
        <h3>4.选择整改人</h3>
        <van-cell-group inset>
          <van-field
          v-model="faceList.handleUserName"
          label="整改人"
          placeholder="请选择整改人"
          readonly
          @click="type != 3 ? showPicker = true : ''"></van-field>          
        </van-cell-group>
        <h3>5.整改措施</h3>
        <van-cell-group inset>
          <van-field :disabled="type == 3" v-model="faceList.handleMethod" placeholder="请输入整改措施" type="textarea" rows="3" autosize></van-field>
        </van-cell-group>
        <h3>6.整改照片</h3>
        <van-cell-group inset>
          <van-uploader
          v-if="type != 3"
          v-model="fileList"
          :after-read="afterRead"
          :before-read="beforeRead"
          :preview-options='{closeable:true}'></van-uploader>
          <a-image v-else :width="150" v-for="item in (faceList.imgsHandleIdBase64)" :src="'data:image/jpg;base64,' + item"></a-image>
        </van-cell-group>
        <h3>7.流程展示</h3>
        <van-cell-group inset>
          <van-steps direction="vertical" :active="active">
            <van-step v-for="item in JSON.parse(faceList.handleFlow)">
              <div class="role">{{ item.roleName }}</div>
              <div class="time">{{ item.time }}</div>
              <p class="title">{{ item.flowName }}</p>
              <p class="method">{{ item.name }}</p>
            </van-step>
          </van-steps>
        </van-cell-group>
        <br>
        <div class="btn" v-if="type != 3">
          <van-button type="primary" v-if="!confirm" @click="doSubmit">提交处理</van-button>
          <van-button type="danger" v-else @click="doSubmit">事件办结</van-button>
        </div>
      </van-form>

      <van-popup v-model:show="showPicker" round position="bottom">
        <van-field
          placeholder="查询名称"
          v-model="zhenggaiSelect"
          left-icon="search"
          @update:model-value="handleSearchNationsOrder(zhenggaiSelect)"
        />
        <van-picker
          :columns="zhenggaiList"
          @cancel="showPicker = false"
          @confirm="onConfirm"
          :columns-field-names="{text:'nickname', value: 'id'}"
        />
      </van-popup>
    </a-spin>
  </template>
  
  <script setup>
  import { ref, onMounted, inject } from "vue"
  import { useRoute } from "vue-router";
  import { Popup as VanPopup, CellGroup as VanCellGroup, Uploader as VanUploader, Field as VanField, Steps as VanSteps, Step as VanStep } from "vant";
  import router from "@/route/index.js";
  import { getHiddentrouble, photoUploadBase64, updateHiddentrouble } from "@/api/common.js";
  import * as imageConversion from 'image-conversion'
  
  const loading = ref(false),
    toast = inject("toast"),
    route = useRoute();
  const faceList = ref({
    imgsIdBase64: "null",
    handleFlow: "null"
  });
  const formRef = ref(null);
  const userList = ref([]);
  const zhenggaiList = ref([]);
  const zhenggaiSelect = ref(null);
  const fileList = ref([]);
  const active = ref(1);
  const showPicker = ref(false);
  const confirm = ref(0);
  const type = ref(0);
  const userInfo = ref(JSON.parse(localStorage.getItem("SAVE_USER_INFO")));
  
  onMounted(() => {
    getList()
    type.value = route.query.type
  })
  
  function getList() {
    loading.value = true
    let obj = {
      userId: userInfo.value.userId,
      recordId: route.query.id
    }
    getHiddentrouble(obj).then(res => {
      loading.value = false
      faceList.value = res.data
      userList.value = res.userList
      confirm.value = res.confirm
      active.value = JSON.parse(res.data.handleFlow).length - 1
      res.data.imgsHandleIdBase64 = JSON.parse(res.data.imgsHandleIdBase64) ? JSON.parse(res.data.imgsHandleIdBase64) : []
      res.data.imgsHandleId = JSON.parse(res.data.imgsHandleId) ? JSON.parse(res.data.imgsHandleId) : []
      res.data.imgsHandleIdBase64.forEach((item, index) => {
        fileList.value.push({ content: 'data:image/jpg;base64,' + item, name: res.data.imgsHandleId[index], isImage: true, url: 'data:image/jpg;base64,' + item })
      })
    }, err => {
      loading.value = false
    })
  }

  function handleSearchNationsOrder(val) {
    zhenggaiList.value = []
    userList.value.forEach(item => {
      if(item.nickname.indexOf(val) != -1) {
        zhenggaiList.value.push(item)
      }
    })
  }

  function beforeRead(file) {
    return new Promise((resolve, reject) => {
      imageConversion.compressAccurately(file, 200).then(res => {
        res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
        resolve(res)
      })
    });
  }

  function onConfirm(val) {
    showPicker.value = false
    faceList.value.handleUserId = val.id
    faceList.value.handleUserName = val.nickname
  }

  function afterRead(file) {
    uploadFile(file);
  }
  function uploadFile(file) {
    file.status = "uploading";
    loading.value = true;
    apiUpLoadImg(file);
  }
  function getBase64(file) {
    return new Promise(function (resolve, reject) {
      const reader = new FileReader();
      let imgResult = "";
      reader.readAsDataURL(file);
      reader.onload = function () {
        imgResult = reader.result;
      };
      reader.onerror = function (error) {
        reject(error);
      };
      reader.onloadend = function () {
        resolve(imgResult);
      };
    });
  }

  function apiUpLoadImg(file) {
    getBase64(file.file).then(res => {
      let obj = {
        base64: res,
        recordId: route.query.id
      }
      //接口需要传的参数
      photoUploadBase64(obj).then(res => {
        file.status = "success";
        file.msg = res.message;
        loading.value = false;
      },err=>{
        loading.value = false
        console.log(err)
      })    
    })
  }

  function doSubmit() {
    formRef.value.submit();
  }

  function onSubmit() {
    // if(!faceList.value.handleUserId) {
    //   toast.msg("请选择整改人！")
    //   return
    // }
    let obj = {
      userId: userInfo.value.userId,
      recordId: route.query.id,
      handleUserId: faceList.value.handleUserId,
      handleMethod: faceList.value.handleMethod,
      imgsHandleId: []
    }
    fileList.value.forEach(item => {
      if(item.content && item.name) {
        obj.imgsHandleId.push(item.name)
      } else {
        obj.imgsHandleId.push(item.msg)
      }
    })
    loading.value = true
    updateHiddentrouble(obj).then(res => {
      if(res.code == 200) {
        toast.msg(res.message)
        loading.value = false 
        router.push("/photo?login=true")
      } else {
        toast.msg(res.message)
        loading.value = false
      }
    }, err => {
      toast.msg(err)
      loading.value = false
    })
  }
  </script>
  
  <style lang="less" scoped>
  :deep(.van-field__label) {
    width: 50vw;
  }
  :deep(.van-uploader) {
    margin: 8px 0 0 10px;
  }
  .btn {
    margin: 0 16px;
  
    button {
      width: 100%;
    }
  
  }
  
  :deep(.van-uploader__preview) {
    margin-right: 5px;
  }
  
  .watch-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 10px 0 0 0;
    background-color: #fff;
    margin: 20px;
    border-radius: 20px;
    font-family: adobe;
    .btn {
      width: 150px;
      height: 150px;
      background: linear-gradient(to bottom, rgb(71, 160, 248), rgb(59, 135, 246));
      border-radius: 150px;
      font-family: abode;
      font-size: 20px;
      color: #fff;
      font-weight: 500;
      text-align: center;
      padding-top: 45px;
      margin: 10px auto;
      text-shadow: 0px 0px 1px #fff;
      .time {
        font-size: 16px;
        color: rgb(145, 200, 250);
      }
    }
    .watch-list {
      margin: 20px 30px;
      text-align: center;
      h3 {
        color: #252525;
        font-size: 20px;
        font-weight: bold;
        text-align: left;
      }
      .list {
        line-height: 40px;
        color: #000000;
        font-size: 16px;
        padding: 0 15px;
        letter-spacing: 2px;
        white-space: nowrap;
      }
    }
  }

  .home-title {

    margin-left: 15px;
    margin-top: 20px;

    h1 {
      font-weight: 700;
      margin: 0;
    }

    h3 {
      font-weight: 700;
      margin: 0;
      margin-left: 10px;
    }

    span {
      display: block;
      margin-left: 15px;
      margin-bottom: 3px;

      font.yellow {
        border: 1px solid #ffea00;
        color: #ffea00;
        padding: 1px 3px;
      }

      font.orange {
        border: 1px solid orange;
        color: orange;
        padding: 1px 3px;
      }

      font.red {
        border: 1px solid red;
        color: red;
        padding: 1px 3px;
      }

    }

    }
  
  @font-face {
    font-family: adobe;
    src: url(../../assets/fonts/苹方黑体-中黑-简.woff);
  }
  :deep(.ant-spin-container) {
    margin-bottom: 60px;
  }

  .role {
    width: 40px;
    height: 40px;
    float: left;
    background-color: #5193f3;
    border-radius: 3px;
    color: #fff;
    font-size: 16px;
    line-height: 20px;
    text-align: center;
    font-weight: normal;
    font-family: adobe;
    margin-right: 8px;
  }

  .time {
    float: right;
    font-family: regular;
    color: #a0a0a0;
    font-size: 15px;
  }

  p {
    margin: 0;
    padding: 0;
    margin-left: 5px;
  }

  p.title {
    font-family: medium;
    color: #343434;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 5px;
  }

  p.method {
    font-family: regular;
    color: #a0a0a0;
    font-size: 15px;
    font-weight: 400;
    height: 18px;
  }
  h3 {
    font-weight: 700;
    margin: 5px 15px;
  }
  </style>